﻿import type { RequestOptions } from '@@/plugin-request/request';
import type { RequestConfig } from '@umijs/max';
import { AxiosResponse } from 'axios';
import { message, notification } from 'antd';
import {LocalStorageService} from "@/utils";

// 错误处理方案： 错误类型
enum ErrorShowType {
  SILENT = 0,
  WARN_MESSAGE = 1,
  ERROR_MESSAGE = 2,
  NOTIFICATION = 3,
  REDIRECT = 9,
}

interface FormattedResponse {
  data: any;
  success: boolean;
  message: string;
}

// 与后端约定的响应数据格式
interface ResponseStructure {
  success: boolean;
  data: any;
  message: string;
  status: number;
}

/**
 * @name 错误处理
 * pro 自带的错误处理， 可以在这里做自己的改动
 * @doc https://umijs.org/docs/max/request#配置
 */
export const errorConfig: RequestConfig = {
  // 错误处理： umi@3 的错误处理方案。
  errorConfig: {
    // 错误抛出
    errorThrower: (res) => {
      const { success } =
        res as unknown as ResponseStructure;
      if (!success) {
        throw res; // 抛出自制的错误
      }
    },
    // 错误接收及处理
    errorHandler: (error: any) => {
      throw error
    },
  },

  // 请求拦截器
  requestInterceptors: [
    (config: RequestOptions) => {
      if (!config.headers) {
        config.headers = {};
      }

      const loginInfo = LocalStorageService.getItem('loginInfo');
      if (null !== loginInfo && loginInfo.token) {
        const { token } = loginInfo;
        config.headers['Authorization'] = `${token}`;
      }

      const url = config?.url;
      return { ...config, url };
    },
  ],

  /// 响应拦截器
  responseInterceptors: [
    (response): AxiosResponse => {

      // console.log('响应拦截器触发。。。。', response)

      if (200 !== response.status) {
        console.log('not 200', response.data);
        // todo... 处理
      }

      // todo... 返回401或403，在这里抛出异常，到error拦截器中处理登出操作
      const responseData = response.data as unknown as ResponseStructure;

      let formattedResponse: FormattedResponse = {
        data: null,
        success: false,
        message: ''
      };

      if (0 !== responseData.status) {
        formattedResponse.message = responseData.message;
        formattedResponse.data = responseData
        return {
          ...response,
          data: formattedResponse
        };
      }

      formattedResponse = {
        data: responseData.data,
        success: true,
        message: responseData.message
      };
      return {
        ...response,
        data: formattedResponse
      };
    },
  ],
};
